<template>
  <div class="login-page">
    <img class="login-bg" :src="loginBg" alt="">
    <div v-show="!isWeixin">
      <input class="mobile-input" placeholder="请输入手机号" type="text" v-model="mobile">
      <input class="mobile-input" v-if="alreadySendSms" placeholder="请输入手机验证码" type="text" v-model="smsCode">
      <van-button class="check-button" @click="debounceGetToken">{{alreadySendSms ? '确定验证码' : '一键登录'}}</van-button>
    </div>
    <div v-show="debug">
      <p>{{proressMsg}}</p>
      <p>{{AfterCheckTokenMsg}}</p>
      <van-button @click="isWeixin = !isWeixin">{{isWeixin? '微信' : '非微信'}}</van-button>
      <van-button @click="init">init</van-button>
      <p>{{openid}}</p>
    </div>
    <p style="color: #f51e37;text-align: center">{{errorMsg}}</p>
    <!-- <van-button @click="debug = !debug">调试</van-button>
    <van-button @click="goArchitectureShow">调试</van-button> -->
    <!-- <valiteMobile v-show="architectureValiteVisible" @goArchitectureShow="goArchitectureShow"></valiteMobile> -->
  </div>
</template>

<script>

import wxShareMixin from '@/utils/wxShareMixin.js'
import NEQuickPass from 'netease-quickpass-sdk'
import handle from '@/utils/handle.js'

function debounce(fun, delay) {
  let timer
  return function() {
    clearTimeout(timer)
    let args = arguments
    timer = setTimeout(() => {
      fun(...args).call(this)
    }, delay);
  }
}

export default {
  mixins: [wxShareMixin],
  data() {
    return {
      debug: false,
      userId: '',
      mobile: '',
      smsCode: '',
      proressMsg: 'nothing',
      AfterCheckTokenMsg: 'nothing',
      loginBg: require('@/assets/img/loginBg.png'),
      alreadySendSms: false, 
      // alreadySendSms: true, // todo 恢复为false
      isWeixin: false,
      person_id: '',
      errorMsg: '',
      architectureValiteVisible: false, 
      // architectureValiteVisible: true, // todo 恢复为false
      isLogin:false,//判断是否登录
    }
  },
  components: {
    
  },
  beforeRouteLeave(to, from, next){//调到登录页面(只有一次的问题)
    if(this.showType!=='architecture'){
        this.checkBindMobile().then(res=>{//4001 未来登录 3010 未绑定(拿到openid的情况下)
        // console.log(res);
        let code=res.data.code
        console.log('--------------路由--------------------------',res);
        if(code==3010){
          this.$router.replace({
            name: 'bindPhone',
            query: {
              cj_id: this.cj_id,
            }
          })
        }else if(code==4001){//这里未登录还是放到下面去判断

        }
      }).catch(err=>{

      })
    }
    next()
  },
  computed: {
    cj_id(){//抽奖
      return this.$route.query["cj_id"];
    },
    liveId() {
      return this.$route.query["live_id"];
    },
    openid() {
      let openid = this.$route.query['openid']
      return openid ? (openid.indexOf(",") >= 0 ? openid.split(",")[1] : openid) : "";
    },
    unionid() {
      return this.$route.query.unionid || localStorage.getItem("unionid")
    },
    showType() {
      return this.$route.query.showType || ''
      // 'architecture' 代表中国建筑学会的直播，需要进行中国建筑学会的手机验证
    }
  },
  mounted() {
    if (this.showType == 'architecture') {
      const linkObj = {
        title: '2020中国建筑学会学术年会直播火热进行中', // 分享标题
        desc: '2020中国建筑学会学术年会10月28-30日在深圳召开，线上直播邀您一起观看。',
        link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: 'http://img3.job1001.com/yewen2020/images/architecture/homeShare.png', // 分享图标
      };
      this.$nextTick(() => {
        this.wxConfig(linkObj);
      });
    }
  },
  created() {
    // alert(window.location.href)
    var ua = navigator.userAgent.toLowerCase();
    this.isWeixin = ua.indexOf("micromessenger") != -1;
    this.checkLogin()
    // this.init()  //使用这个可能会存在重复多次跳转的问题;
    this.debounceGetToken = debounce(this.getToken, 1000)
  },
  methods: {
    init() {
      if (this.isWeixin) {//this.isWeixin
        if(!this.openid){//先跳转到其他页面,在跳转回来并在URL上拼接上对应信息,再从url上那取对应信息(bug 会存在重复拼接)
          var jump = encodeURIComponent(window.location.href);
          window.location.href =
            // 'http://www.yl1001.com/personServe/oauth_connect/login.php?connect_source=wechat&act=forward&http_referer=' + //线上
            // 'http://1001.yl1001.com/personServe/oauth_connect/login.php?connect_source=wechat&act=forward&http_referer=' +  //测试
            process.env.oauth_URL+
            jump;
          return;
        }
        
        if (this.unionid) {
          if(this.unionid==',')return;
          window.localStorage.setItem('unionid',this.unionid)
        }
        if (this.openid) {
          console.log('信息',process.env.oauth_URL,this.openid,this.unionid);
          window.localStorage.setItem('openid',this.openid)
          this.getUserInfoByOpenid();   
        }
      }
    },
    checkLogin() {
      this.$http({
        url: this.$http.adornUrl(`index/login/checkLoginStatus`,'proxyPhp'),
      }).then((res) => {
        if(res.data.code==200){
          localStorage.setItem("cks_sy", res.data.data.cks_sy);
          localStorage.setItem("person_id", res.data.data.person_id);
          this.goLiveView()
        } else {
          this.init()
        }
      }).catch(err => {
        this.init()
      })
    },
    goLiveView(){
      if (this.showType == 'architecture') {
        this.architectureShowDeal()
        return;
      }
      this.$router.replace({
        name: 'show',
        query: {
          cj_id: this.cj_id,
          // person_id: this.person_id,//存本地,不在URL上显示
          // userId: this.userId,
          // openid: this.openid,
        }
      })
    },
    // 微信登录相关
    getUserInfoByOpenid() {
      console.log('三个id',this.openid,this.unionid,this.$route.query['openid']);
      this.$http({
        url: this.$http.adornUrl("index/login/getWechatInfo", 'proxyHL'),
        method: "post",
        data: {
          openid: this.openid||localStorage.getItem("openid"),
          unionid: this.unionid||this.openid,
        },
      }).then(({ data }) => {//bug 现在有部分有url上openid会导致拉不起来授权,以至于登录不进去
        console.log('登录信息id',data);
        if (data.code == 200) {
            localStorage.setItem('cks_sy',data.data.cks_sy)
            localStorage.setItem('person_id',data.data.person_id)
            this.weChatLogin(data.data)
        } else {
          this.errorMsg = data.status_desc
        }
      });
    },
    weChatLogin(userInfo) {
      if(this.openid){
          let info = {
            live_id: this.liveId,
            userInfo,
          };
        info["live_id"] = this.liveId;
        console.log(info);
        this.$http({
          url: this.$http.adornUrl("/sys/liveuser/weChatLogin"),
          method: "post",
          data: {
            info: JSON.stringify(info),
          },
        }).then(({ data }) => {
          console.log('登录信息id',data);
          if(data.code==200){
             this.userId = data.data.userId; //拿到id
             localStorage.setItem('userId',this.userId)
             this.goLiveView()
          } else {
            this.errorMsg = data.status_desc
          }
        });
      }
    },


    // 一键登录
    getToken() {
      if (this.alreadySendSms) {
        this.checkSms()
        return
      }
      if(!handle.checkPhone(this.mobile)){
        return this.$toast('请输入正确手机号')
      }
      var sdk = new NEQuickPass('302abaf35e0747cc80b4ac61a0f00ebc');
      console.log(this.mobile);
      let that  = this;
      sdk.getToken(this.mobile, function (err, data) {
        console.log('NEQuickPass-token-data---->', data);
        if (err) {
          // 发送短信
          that.proressMsg = '发送短信中'
          // that.$toast('发送短信中')
          console.log('duanxin-------》', );
          that.sendSmsCode()
          return
        }
        const params =  {"mobile": that.mobile, "type":10, "accessToken": data.accessToken, "token": data.token}
        that.proressMsg = params
        that.checkquickPassToken(data)
      })
    },
    sendSmsCode() {
      this.$http({
        // url: 'http://m.1001.job1001.com/index/ologin/?detail=checkMobile',
        // url: 'https://m5test.yl1001.com/controller/v1/public/index.php/index/login/checkMobile',
        url: this.$http.adornUrl(`index/login/checkMobile`,'proxyHL'),
        data: {"mobile": this.mobile, "type":20},
        method: "post",
      }).then(({data}) => {
        this.proressMsg = data
        if (data.code == 200) {
          this.$toast('短信发送成功,请稍后')
          this.alreadySendSms = true;
          console.log('data', data);
        } else {
          this.errorMsg = data.status_desc
        }
      })
    },
    checkquickPassToken(data) {
      this.proressMsg = {
          type: '验证token中',
          params: {"mobile": this.mobile, "type":10, "accessToken": data.accessToken, "token": data.token},
      }
      console.log('proressMsg', this.proressMsg);
      this.$http({
        url: this.$http.adornUrl(`index/login/checkMobile`,'proxyHL'),
        method: "post",
        data: {"mobile": this.mobile, "type":10, "accessToken": data.accessToken, "token": data.token},
        type:'POST',
      }).then(({ data }) => {
        if (data.code == 200) {
          if (data.data.person_id||data.data.cks_sy) {
            this.person_id = data.data.person_id
            localStorage.setItem('person_id',this.person_id)
            localStorage.setItem('cks_sy',data.data.cks_sy)//以后用这个代替person_id
            this.goLiveView()
          }
          if (data.data.send_sms == 1) {
            this.alreadySendSms = true;
          }
        } else {
          this.errorMsg = data.status_desc
        }
        this.AfterCheckTokenMsg = {
          type: '验证了token',
          data
        }
        console.log('this.AfterCheckTokenMsg', this.AfterCheckTokenMsg);
      }).catch(err => {
        this.AfterCheckTokenMsg = {
          type: '验证token失败',
          data: err,
        }
        console.log('this.AfterCheckTokenMsg', this.AfterCheckTokenMsg);
      })
    },
    checkSms() {
      const data = {
        sms_code: this.smsCode,
        mobile: this.mobile,
      }
      this.proressMsg = data
      this.$http({
        // url: 'https://m5test.yl1001.com/controller/v1/public/index.php/index/login/checkSms',
        url: this.$http.adornUrl(`index/login/checkSms`,'proxyHL'),
        data,
        method: "post",
      }).then(({data}) => {
        console.log('data', data);
        if (data.code == 200){
          this.person_id = data.data.person_id
          localStorage.setItem('person_id',this.person_id)
          localStorage.setItem('cks_sy',data.data.cks_sy)////以后用这个代替person_id
          this.goLiveView()
        } else {
          this.errorMsg = data.status_desc
        }
        this.proressMsg = data
      })
      
    },

    // 建筑学会直播相关
    goArchitectureShow() {
       return this.$notify('抱歉,活动已过期');//业问的过期不让访问
      console.log('this.liveId,', this.liveId,);
      this.$router.replace({
        name: 'show',
        query: {
          cj_id: this.cj_id,
          person_id: this.person_id,
          userId: this.userId,
          openid: this.openid,
          showType: 'architecture',
        }
      })
    },
    architectureShowDeal() {
      return this.$notify('抱歉,活动已过期');//业问的过期不让访问

      if (localStorage.architecturePassMobile) {
        // 缓存手机是否在上报数据，如果在上报数据，则重新输入手机号
        this.$http({
          url: this.$http.adornUrl("/building/building/addPersonStatInfo", 'proxyHtyLocal'),
          method: "post",
          data: {
            live_id: this.liveId,
            person_id: this.person_id || localStorage.person_id,
            mobile: localStorage.architecturePassMobile,
          },
        }).then(( {data} ) => {
          if (data.code == 1020) {
            this.$notify(`${localStorage.architecturePassMobile}正在被其他用户使用,请重新绑定手机号`);
            this.architectureValiteVisible = true;
            return;
          }
          if (data.code != 200) {
            this.$notify(`检测上报失败，请重新刷新页面: ${data.status_desc}`); 
            return;
          }
          
          this.$router.replace({
            name: 'show',
            query: {
              cj_id: this.cj_id,
              person_id: this.person_id,
              userId: this.userId,
              openid: this.openid,
              showType: 'architecture',
            }
          })
        })
        return
      }
      this.architectureValiteVisible = true;
    },

    checkBindMobile(){//检测用户是否绑定过手机号(这个放在直播页面进行判断跳转,是否可以根据路由守卫来直接判断)
      return this.$http({
        url: this.$http.adornUrl('index/user/checkBindMobile','proxyPhp'),
        method: "post",
      })
    },
  }
}
</script>

<style scoped>
.login-page{
  background: #f2f2f2;
  min-height: 100vh;
}
.login-bg{
  width: 231px;
  display: block;
  margin: 0  auto 50px;
  padding-top: 80px;
}
.mobile-input{
  border: none;
  border-radius: 30px;
  height: 48px;
  line-height: 48px;
  width: 250px;
  margin: 20px auto;
  display: block;
  padding: 0 16px;
}
.check-button{
  width: 280px;
	height: 48px;
  color: #fff;
  line-height: 48px;
  text-align: center;
  display: block;
  margin: 0 auto;
  font-size: 19px;
	background-image: linear-gradient(180deg, 
		#f51e37 0%, 
		#f20622 52%, 
		#f90421 78%);
	box-shadow: 0px 5px 12px 0px 
		rgba(255, 0, 30, 0.1);
	border-radius: 48px;
}
</style>